package com.aolei.mallshop.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.aolei.common.utils.HttpUtils;
import com.aolei.mallshop.member.dao.MemberLevelDao;
import com.aolei.mallshop.member.entity.MemberLevelEntity;
import com.aolei.mallshop.member.exception.PhoneExistException;
import com.aolei.mallshop.member.exception.UsernameExistException;
import com.aolei.mallshop.member.vo.GiteeUserVo;
import com.aolei.mallshop.member.vo.MemberLoginVo;
import com.aolei.mallshop.member.vo.MemberRegistVo;
import com.aolei.mallshop.member.vo.SocialUser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aolei.common.utils.PageUtils;
import com.aolei.common.utils.Query;

import com.aolei.mallshop.member.dao.MemberDao;
import com.aolei.mallshop.member.entity.MemberEntity;
import com.aolei.mallshop.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();

        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());

        entity.setNickname(vo.getUsername());
        entity.setUsername(vo.getUsername());

        //jwt
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        entity.setMobile(vo.getPhone());
        entity.setGender(0);
        entity.setCreateTime(new Date());

        this.baseMapper.insert(entity);
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException{
        int count = this.count(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count>0){
            throw new UsernameExistException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        Integer mobile = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile>0){
            throw new PhoneExistException();
        }

    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (entity==null){
            return null;
        }else{

            String password1 = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, password1);
            if (matches){
                return entity;
            }else{
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token",socialUser.getAccess_token());
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(),map);

        if(response.getStatusLine().getStatusCode()==200){

            HttpEntity entity = response.getEntity();
            String json = EntityUtils.toString(entity);
            GiteeUserVo giteeUserVo = JSON.parseObject(json, GiteeUserVo.class);

            MemberEntity social_uid = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", giteeUserVo.getId()));
            if (social_uid!=null){
                social_uid.setAccessToken(socialUser.getAccess_token());
                social_uid.setExpiresIn(socialUser.getExpires_in());
                this.updateById(social_uid);
                return social_uid;
            }else {
                MemberEntity memberEntity = new MemberEntity();
                memberEntity.setSocialUid(giteeUserVo.getId());
                memberEntity.setUsername(giteeUserVo.getName());
                memberEntity.setEmail(giteeUserVo.getEmail());
                memberEntity.setAccessToken(socialUser.getAccess_token());
                memberEntity.setExpiresIn(socialUser.getExpires_in());
                memberEntity.setCreateTime(new Date());
                memberEntity.setUrl(giteeUserVo.getAvatar_url());
                this.save(memberEntity);
                return memberEntity;
            }
        }
        return null;
    }

}